// app/service/user.js
const Service = require("egg").Service;
const fs = require("fs-extra");
const p = require("path");
const { Op } = require("sequelize");
const _ = require("loadsh");
const md5 = require("md5");
const needle = require("needle");

class WebService extends Service {
  async searchByPreset(params) {
    let { value } = params;
    let ret = await this.ctx.model.TeleplayData.findAll({
      where: {
        name: {
          [Op.like]: `%${value}%`,
        },
      },
      limit: 10,
      offset: 1,
    });
    return { data: { rows: ret }, msg: "获取数据预设成功" };
  }

  checkFolder(folder_path) {
    let has_folder = fs.pathExistsSync(folder_path);
    if (!has_folder) {
      return {
        msg: "电视剧文件夹不存在，请检查数据后重新添加",
        code: 400,
      };
    }
    let files = fs
      .readdirSync(folder_path)
      .filter(a => p.extname(a).indexOf(".mp4") != -1)
      .sort((a, b) => Number(a.split(".")[0]) - Number(b.split(".")[0]))
      .map(a => p.join(folder_path, a));
    if (files.length < 1) {
      return {
        msg: "文件夹中不存在视频数据请检查后重试。",
        code: 400,
      };
    }

    return files;
  }

  async deleteTeleplay(params) {
    let { id, word, name } = params;
    try {
      let target = p.join(this.config.space.tv_path, word);
      this.ctx.helper.deleteFolderRecursive(target);
      await this.ctx.model.TeleplayList.destroy({
        where: {
          tv_id: id,
        },
      });
      await this.ctx.model.Teleplay.destroy({
        where: {
          id,
        },
      });
      await this.app.model.Notifi.create({
        title: "删除操作",
        content: `删除电视剧 ${name} 任务完成`,
      });
      return { msg: "删除电影数据成功" };
    } catch (e) {
      console.log(e);
      return { msg: "删除电影数据失败" };
    }
  }

  async addTeleplay(params) {
    let { tv_data, folder_path, save_type, data_type } = params;
    let result = { data: {}, msg: "保存数据成功", code: 200 };
    let check_result = this.checkFolder(folder_path);
    if (!Array.isArray(check_result)) {
      return check_result;
    }
    let isHas = await this.ctx.model.Teleplay.findOne({
      where: { word: tv_data.word },
    });
    if (isHas != null) {
      result.msg = "您添加的电视剧已存在请不要重复添加";
      result.code = 400;
      return result;
    }
    if (data_type != "input") {
      let picRet = await needle("get", tv_data.pic);
      let name = tv_data.word + ".png";
      let savePath = p.join(this.config.space.tv_img_space, name);
      fs.writeFileSync(savePath, picRet.body);
      tv_data.pic = name;
    }
    let tv_ret = await this.ctx.model.Teleplay.create({
      ...tv_data,
    });
    this.disposeTeleplayTask(check_result, {
      id: tv_ret.id,
      name: tv_data.name,
      word: tv_data.word,
      save_type,
    });
    return result;
  }

  async disposeTeleplayTask(files, tv_data) {
    let { config, app } = this;
    let { id, name, word, save_type } = tv_data;
    let target_path = p.join(config.space.tv_path, word);
    if (!fs.pathExistsSync(target_path)) {
      fs.mkdirSync(target_path);
    }
    for (let file of files) {
      let file_name = p.parse(file).name;
      let job = {
        idx: file_name,
        tv_id: id,
        tv_name: name,
        play_name: `${name}_第${file_name}集`,
        source: file,
        ffmpeg_path: config.space.ffmpeg_path,
        tv_path: target_path,
        save_type,
      };
      this.app.messenger.sendToAgent("add-tv", job);
      // this.tvMp4Task(job);
    }
  }
  async getTeleplayList(params) {
    let { limit, offset, query } = params;
    let where = {};
    if (query?.show != undefined) {
      where.show = query.show;
    }
    if (query?.name != undefined) {
      where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }
    try {
      let ret = await this.ctx.model.Teleplay.findAndCountAll({
        where,
        limit,
        offset,
      });

      return { data: ret, msg: "获取电视剧列表成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电视剧列表失败", code: 400 };
    }
  }

  async getClassify(params) {
    try {
      let where = {};
      if (params?.show != undefined) {
        where.show = params.show;
      }
      let ret = await this.ctx.model.TeleplayClass.findAll({
        where,
      });
      let result = ret.sort((a, b) => a.idx - b.idx);
      return { data: result, msg: "获取电视剧分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电视剧分类失败", code: 400 };
    }
  }

  async addClassify(params) {
    try {
      let ret = await this.ctx.model.TeleplayClass.create({ ...params });
      return { data: ret, msg: "添加电视剧分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "添加电视剧分类失败", code: 400 };
    }
  }

  async deleteClassify(params) {
    try {
      let ret = await this.ctx.model.TeleplayClass.destroy({
        where: {
          id: params.id,
        },
      });
      return { data: ret, msg: "删除电视剧分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "删除电视剧分类失败", code: 400 };
    }
  }

  async updateClassify(params) {
    try {
      await this.ctx.model.TeleplayClass.update(
        { ...params },
        {
          where: {
            id: {
              [Op.eq]: params.id,
            },
          },
        }
      );
      return { msg: "更新电视剧分类成功" };
    } catch (e) {
      console.log(e);
      return { msg: "更新电视剧分类失败", code: 400 };
    }
  }

  async updateTeleplayInfo(params) {
    try {
      await this.ctx.model.Teleplay.update(
        { ...params },
        {
          where: {
            id: params.id,
          },
        }
      );
      return { msg: "更新电视剧信息成功" };
    } catch (e) {
      return { msg: "更新电视剧信息失败", code: 400 };
    }
  }

  async getTeleplayInfo(data) {
    try {
      let { id } = data;
      let ret = await this.ctx.model.Teleplay.findByPk(id);
      let ret2 = await this.ctx.model.TeleplayList.findAll({
        raw: true,
        where: {
          tv_id: id,
        },
      });
      ret.teleplay_list = ret2.sort((a, b) => Number(a.idx) - Number(b.idx));
      return { data: ret, msg: "获取电影详情成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电影详情失败", code: 400 };
    }
  }

  async getTeleplayPlay(data) {
    try {
      let { idx, id } = data;
      let ret = await this.ctx.model.Teleplay.findByPk(id);
      let listCount = await this.ctx.model.TeleplayList.count({
        where: {
          tv_id: {
            [Op.eq]: id,
          },
        },
      });
      let ret2 = await this.ctx.model.TeleplayList.findOne({
        where: {
          tv_id: id,
          idx,
        },
      });
      delete ret2.id;
      let dat = { ...ret, ...ret2, count: listCount };
      return { data: dat, msg: "获取电视剧详情成功" };
    } catch (e) {
      console.log(e);
      return { msg: "获取电视剧详情失败", code: 400 };
    }
  }
}

module.exports = WebService;
